//! Pipit 标准库模块化集成
//! 
//! 本文件实现了对所有标准库函数的模块化注册和调用处理。

use std::collections::HashMap;
use std::ffi::{CString, c_char, c_int, c_double, c_void, CStr};
use std::time::{SystemTime, UNIX_EPOCH};
use std::fs;
use std::path::Path;
use std::io::{self, Read, Write};

use crate::vm::VirtualMachine;
use crate::vm::Value;
use crate::stdlib_registry::StdlibRegistry;

/// 标准库模块配置
pub struct StdlibModuleConfig {
    pub enable_io: bool,
    pub enable_math: bool,
    pub enable_string: bool,
    pub enable_os: bool,
    pub enable_syscall: bool,
    pub enable_concurrent: bool,
    pub enable_json: bool,
    pub enable_collections: bool,
    pub enable_crypto: bool,
    pub enable_datetime: bool,
    pub enable_common: bool,
}

impl Default for StdlibModuleConfig {
    fn default() -> Self {
        Self {
            enable_io: true,
            enable_math: true,
            enable_string: true,
            enable_os: true,
            enable_syscall: true,
            enable_concurrent: true,
            enable_json: true,
            enable_collections: true,
            enable_crypto: true,
            enable_datetime: true,
            enable_common: true,
        }
    }
}

/// 标准库函数注册表
pub struct StandardLibrary {
    registry: StdlibRegistry,
    config: StdlibModuleConfig,
}

impl StandardLibrary {
    /// 创建新的标准库实例
    pub fn new(config: StdlibModuleConfig) -> Self {
        Self {
            registry: StdlibRegistry::new(),
            config,
        }
    }
    
    /// 将所有启用的标准库函数注册到虚拟机
    pub fn register_all(&self, vm: &mut VirtualMachine) {
        // 注册常用标准库函数
        if self.config.enable_common {
            self.register_common_functions(vm);
        }
        
        // 注册IO模块函数
        if self.config.enable_io {
            self.register_io_functions(vm);
        }
        
        // 注册Math模块函数
        if self.config.enable_math {
            self.register_math_functions(vm);
        }
        
        // 注册String模块函数
        if self.config.enable_string {
            self.register_string_functions(vm);
        }
        
        // 注册OS模块函数
        if self.config.enable_os {
            self.register_os_functions(vm);
        }
        
        // 注册Syscall模块函数
        if self.config.enable_syscall {
            self.register_syscall_functions(vm);
        }
        
        // 注册Concurrent模块函数
        if self.config.enable_concurrent {
            self.register_concurrent_functions(vm);
        }
        
        // 注册JSON模块函数
        if self.config.enable_json {
            self.register_json_functions(vm);
        }
        
        // 注册Collections模块函数
        if self.config.enable_collections {
            self.register_collections_functions(vm);
        }
        
        // 注册Crypto模块函数
        if self.config.enable_crypto {
            self.register_crypto_functions(vm);
        }
        
        // 注册DateTime模块函数
        if self.config.enable_datetime {
            self.register_datetime_functions(vm);
        }
    }
    
    // 注册常用标准库函数
    fn register_common_functions(&self, vm: &mut VirtualMachine) {
        vm.register_native_function("read_int".to_string(), native_read_int);
        vm.register_native_function("read_float".to_string(), native_read_float);
        vm.register_native_function("get_time".to_string(), native_get_time);
        vm.register_native_function("print".to_string(), native_print);
        vm.register_native_function("println".to_string(), native_println);
        vm.register_native_function("vsnprintf".to_string(), native_vsnprintf);
        vm.register_native_function("rmdir".to_string(), native_rmdir);
    }
    
    // 注册IO模块函数
    fn register_io_functions(&self, vm: &mut VirtualMachine) {
        vm.register_native_function("pipit_fopen".to_string(), native_pipit_fopen);
        vm.register_native_function("pipit_fclose".to_string(), native_pipit_fclose);
        vm.register_native_function("pipit_fread".to_string(), native_pipit_fread);
        vm.register_native_function("pipit_fwrite".to_string(), native_pipit_fwrite);
        vm.register_native_function("pipit_feof".to_string(), native_pipit_feof);
        vm.register_native_function("pipit_file_size".to_string(), native_pipit_file_size);
        vm.register_native_function("pipit_read_file".to_string(), native_pipit_read_file);
        vm.register_native_function("pipit_write_file".to_string(), native_pipit_write_file);
        vm.register_native_function("pipit_file_exists".to_string(), native_pipit_file_exists);
        vm.register_native_function("pipit_remove_file".to_string(), native_pipit_remove_file);
        vm.register_native_function("pipit_rename_file".to_string(), native_pipit_rename_file);
        vm.register_native_function("pipit_getcwd".to_string(), native_pipit_getcwd);
        vm.register_native_function("pipit_mkdir".to_string(), native_pipit_mkdir);
        vm.register_native_function("pipit_rmdir".to_string(), native_pipit_rmdir);
        vm.register_native_function("pipit_get_file_info".to_string(), native_pipit_get_file_info);
        vm.register_native_function("pipit_read_buffer".to_string(), native_pipit_read_buffer);
        vm.register_native_function("pipit_write_buffer".to_string(), native_pipit_write_buffer);
        vm.register_native_function("pipit_line_reader_open".to_string(), native_pipit_line_reader_open);
        vm.register_native_function("pipit_line_reader_next".to_string(), native_pipit_line_reader_next);
        vm.register_native_function("pipit_line_reader_close".to_string(), native_pipit_line_reader_close);
    }
    
    // 注册Math模块函数
    fn register_math_functions(&self, vm: &mut VirtualMachine) {
        vm.register_native_function("pipit_add".to_string(), native_pipit_add);
        vm.register_native_function("pipit_subtract".to_string(), native_pipit_subtract);
        vm.register_native_function("pipit_multiply".to_string(), native_pipit_multiply);
        vm.register_native_function("pipit_divide".to_string(), native_pipit_divide);
        vm.register_native_function("pipit_modulo".to_string(), native_pipit_modulo);
        vm.register_native_function("pipit_power".to_string(), native_pipit_power);
        vm.register_native_function("pipit_sqrt".to_string(), native_pipit_sqrt);
        vm.register_native_function("pipit_abs".to_string(), native_pipit_abs);
        vm.register_native_function("pipit_max".to_string(), native_pipit_max);
        vm.register_native_function("pipit_min".to_string(), native_pipit_min);
        vm.register_native_function("pipit_round".to_string(), native_pipit_round);
        vm.register_native_function("pipit_floor".to_string(), native_pipit_floor);
        vm.register_native_function("pipit_ceil".to_string(), native_pipit_ceil);
        vm.register_native_function("pipit_random".to_string(), native_pipit_random);
        vm.register_native_function("pipit_srand".to_string(), native_pipit_srand);
        vm.register_native_function("pipit_random_range".to_string(), native_pipit_random_range);
        vm.register_native_function("pipit_sin".to_string(), native_pipit_sin);
        vm.register_native_function("pipit_cos".to_string(), native_pipit_cos);
        vm.register_native_function("pipit_tan".to_string(), native_pipit_tan);
        vm.register_native_function("pipit_log".to_string(), native_pipit_log);
        vm.register_native_function("pipit_log10".to_string(), native_pipit_log10);
        vm.register_native_function("pipit_exp".to_string(), native_pipit_exp);
        vm.register_native_function("pipit_random_float".to_string(), native_pipit_random_float);
        vm.register_native_function("pipit_is_prime".to_string(), native_pipit_is_prime);
        vm.register_native_function("pipit_factorial".to_string(), native_pipit_factorial);
        vm.register_native_function("pipit_gcd".to_string(), native_pipit_gcd);
        vm.register_native_function("pipit_lcm".to_string(), native_pipit_lcm);
        vm.register_native_function("pipit_degrees_to_radians".to_string(), native_pipit_degrees_to_radians);
        vm.register_native_function("pipit_radians_to_degrees".to_string(), native_pipit_radians_to_degrees);
    }
    
    // 注册String模块函数
    fn register_string_functions(&self, vm: &mut VirtualMachine) {
        vm.register_native_function("pipit_string_length".to_string(), native_pipit_string_length);
        vm.register_native_function("pipit_string_concat".to_string(), native_pipit_string_concat);
        vm.register_native_function("pipit_string_to_upper".to_string(), native_pipit_string_to_upper);
        vm.register_native_function("pipit_string_to_lower".to_string(), native_pipit_string_to_lower);
        vm.register_native_function("pipit_string_compare".to_string(), native_pipit_string_compare);
        vm.register_native_function("pipit_string_find".to_string(), native_pipit_string_find);
        vm.register_native_function("pipit_string_split".to_string(), native_pipit_string_split);
        vm.register_native_function("pipit_string_replace".to_string(), native_pipit_string_replace);
        vm.register_native_function("pipit_string_trim".to_string(), native_pipit_string_trim);
        vm.register_native_function("pipit_string_substring".to_string(), native_pipit_string_substring);
        vm.register_native_function("pipit_string_starts_with".to_string(), native_pipit_string_starts_with);
        vm.register_native_function("pipit_string_ends_with".to_string(), native_pipit_string_ends_with);
        vm.register_native_function("pipit_string_to_int".to_string(), native_pipit_string_to_int);
        vm.register_native_function("pipit_string_to_double".to_string(), native_pipit_string_to_double);
        vm.register_native_function("pipit_string_format".to_string(), native_pipit_string_format);
        vm.register_native_function("pipit_string_split_free".to_string(), native_pipit_string_split_free);
        vm.register_native_function("strdup".to_string(), native_strdup);
    }
    
    // 注册OS模块函数
    fn register_os_functions(&self, vm: &mut VirtualMachine) {
        vm.register_native_function("pipit_os_system".to_string(), native_pipit_os_system);
        vm.register_native_function("pipit_os_getcwd".to_string(), native_pipit_os_getcwd);
        vm.register_native_function("pipit_os_chdir".to_string(), native_pipit_os_chdir);
        vm.register_native_function("pipit_os_mkdir".to_string(), native_pipit_os_mkdir);
        vm.register_native_function("pipit_os_remove".to_string(), native_pipit_os_remove);
        vm.register_native_function("pipit_os_stat".to_string(), native_pipit_os_stat);
        vm.register_native_function("pipit_os_filesize".to_string(), native_pipit_os_filesize);
        vm.register_native_function("pipit_os_timestamp".to_string(), native_pipit_os_timestamp);
    }
    
    // 注册Syscall模块函数
    fn register_syscall_functions(&self, vm: &mut VirtualMachine) {
        vm.register_native_function("pipit_syscall_read_int".to_string(), native_pipit_syscall_read_int);
        vm.register_native_function("pipit_syscall_read_float".to_string(), native_pipit_syscall_read_float);
        vm.register_native_function("pipit_syscall_read_string".to_string(), native_pipit_syscall_read_string);
        vm.register_native_function("pipit_syscall_read_line".to_string(), native_pipit_syscall_read_line);
        vm.register_native_function("pipit_syscall_print_int".to_string(), native_pipit_syscall_print_int);
        vm.register_native_function("pipit_syscall_print_float".to_string(), native_pipit_syscall_print_float);
        vm.register_native_function("pipit_syscall_print_string".to_string(), native_pipit_syscall_print_string);
        vm.register_native_function("pipit_syscall_print_line".to_string(), native_pipit_syscall_print_line);
        vm.register_native_function("pipit_syscall_getenv".to_string(), native_pipit_syscall_getenv);
        vm.register_native_function("pipit_syscall_system".to_string(), native_pipit_syscall_system);
    }
    
    // 注册Concurrent模块函数
    fn register_concurrent_functions(&self, vm: &mut VirtualMachine) {
        vm.register_native_function("pipit_sleep".to_string(), native_pipit_sleep);
        vm.register_native_function("pipit_thread_create".to_string(), native_pipit_thread_create);
        vm.register_native_function("pipit_thread_join".to_string(), native_pipit_thread_join);
        vm.register_native_function("pipit_thread_id".to_string(), native_pipit_thread_id);
        vm.register_native_function("pipit_mutex_create".to_string(), native_pipit_mutex_create);
        vm.register_native_function("pipit_mutex_destroy".to_string(), native_pipit_mutex_destroy);
        vm.register_native_function("pipit_mutex_lock".to_string(), native_pipit_mutex_lock);
        vm.register_native_function("pipit_mutex_unlock".to_string(), native_pipit_mutex_unlock);
    }
    
    // 注册JSON模块函数
    fn register_json_functions(&self, vm: &mut VirtualMachine) {
        vm.register_native_function("json_create_null".to_string(), native_json_create_null);
        vm.register_native_function("json_create_bool".to_string(), native_json_create_bool);
        vm.register_native_function("json_create_number".to_string(), native_json_create_number);
        vm.register_native_function("json_create_string".to_string(), native_json_create_string);
        vm.register_native_function("json_array_create".to_string(), native_json_array_create);
        vm.register_native_function("json_array_append".to_string(), native_json_array_append);
        vm.register_native_function("json_object_create".to_string(), native_json_object_create);
        vm.register_native_function("json_object_set".to_string(), native_json_object_set);
        vm.register_native_function("json_serialize_string".to_string(), native_json_serialize_string);
    }
    
    // 注册Collections模块函数
    fn register_collections_functions(&self, vm: &mut VirtualMachine) {
        vm.register_native_function("pipit_vector_create".to_string(), native_pipit_vector_create);
        vm.register_native_function("pipit_vector_push_back".to_string(), native_pipit_vector_push_back);
        vm.register_native_function("pipit_vector_get".to_string(), native_pipit_vector_get);
        vm.register_native_function("pipit_vector_size".to_string(), native_pipit_vector_size);
        vm.register_native_function("pipit_vector_destroy".to_string(), native_pipit_vector_destroy);
        vm.register_native_function("pipit_hashmap_create".to_string(), native_pipit_hashmap_create);
        vm.register_native_function("pipit_hashmap_set".to_string(), native_pipit_hashmap_set);
        vm.register_native_function("pipit_hashmap_get".to_string(), native_pipit_hashmap_get);
        vm.register_native_function("pipit_list_create".to_string(), native_pipit_list_create);
        vm.register_native_function("pipit_list_push_back".to_string(), native_pipit_list_push_back);
        vm.register_native_function("pipit_list_get".to_string(), native_pipit_list_get);
        vm.register_native_function("pipit_list_size".to_string(), native_pipit_list_size);
        vm.register_native_function("pipit_stack_create".to_string(), native_pipit_stack_create);
        vm.register_native_function("pipit_stack_push".to_string(), native_pipit_stack_push);
        vm.register_native_function("pipit_stack_pop".to_string(), native_pipit_stack_pop);
        vm.register_native_function("pipit_queue_create".to_string(), native_pipit_queue_create);
        vm.register_native_function("pipit_queue_enqueue".to_string(), native_pipit_queue_enqueue);
        vm.register_native_function("pipit_queue_dequeue".to_string(), native_pipit_queue_dequeue);
    }
    
    // 注册Crypto模块函数
    fn register_crypto_functions(&self, vm: &mut VirtualMachine) {
        vm.register_native_function("pipit_crypto_xor_encrypt".to_string(), native_pipit_crypto_xor_encrypt);
        vm.register_native_function("pipit_crypto_caesar_encrypt".to_string(), native_pipit_crypto_caesar_encrypt);
        vm.register_native_function("pipit_crypto_checksum".to_string(), native_pipit_crypto_checksum);
        vm.register_native_function("pipit_crypto_random_bytes".to_string(), native_pipit_crypto_random_bytes);
        vm.register_native_function("pipit_crypto_base64_encode".to_string(), native_pipit_crypto_base64_encode);
        vm.register_native_function("pipit_crypto_hmac".to_string(), native_pipit_crypto_hmac);
        vm.register_native_function("pipit_crypto_password_strength".to_string(), native_pipit_crypto_password_strength);
    }
    
    // 注册DateTime模块函数
    fn register_datetime_functions(&self, vm: &mut VirtualMachine) {
        vm.register_native_function("pipit_datetime_now".to_string(), native_pipit_datetime_now);
        vm.register_native_function("pipit_datetime_current".to_string(), native_pipit_datetime_current);
        vm.register_native_function("pipit_datetime_create".to_string(), native_pipit_datetime_create);
        vm.register_native_function("pipit_datetime_format".to_string(), native_pipit_datetime_format);
        vm.register_native_function("pipit_datetime_parse".to_string(), native_pipit_datetime_parse);
        vm.register_native_function("pipit_datetime_diff".to_string(), native_pipit_datetime_diff);
        vm.register_native_function("pipit_datetime_add_delta".to_string(), native_pipit_datetime_add_delta);
        vm.register_native_function("pipit_datetime_weekday".to_string(), native_pipit_datetime_weekday);
        vm.register_native_function("pipit_datetime_is_leap_year".to_string(), native_pipit_datetime_is_leap_year);
        vm.register_native_function("pipit_datetime_days_in_month".to_string(), native_pipit_datetime_days_in_month);
        vm.register_native_function("pipit_datetime_to_timestamp".to_string(), native_pipit_datetime_to_timestamp);
        vm.register_native_function("pipit_datetime_from_timestamp".to_string(), native_pipit_datetime_from_timestamp);
        vm.register_native_function("pipit_timer_create".to_string(), native_pipit_timer_create);
        vm.register_native_function("pipit_timer_start".to_string(), native_pipit_timer_start);
        vm.register_native_function("pipit_timer_stop".to_string(), native_pipit_timer_stop);
        vm.register_native_function("pipit_timer_elapsed".to_string(), native_pipit_timer_elapsed);
    }
}

// 纯Rust实现的标准库函数
pub mod stdlib_functions {
    use super::*;
    
    // IO 模块函数实现
    pub fn pipit_fopen(filename: &str, mode: &str) -> *mut FILE {
        // 简化实现，实际应返回FILE指针
        std::ptr::null_mut()
    }
    
    pub fn pipit_fclose(_file: *mut FILE) -> i32 {
        0 // 成功
    }
    
    pub fn pipit_fread(_ptr: *mut c_void, _size: usize, _count: usize, _stream: *mut FILE) -> usize {
        0
    }
    
    pub fn pipit_fwrite(_ptr: *const c_void, _size: usize, _count: usize, _stream: *mut FILE) -> usize {
        0
    }
    
    pub fn pipit_feof(_stream: *mut FILE) -> i32 {
        0
    }
    
    pub fn pipit_file_size(filename: &str) -> i64 {
        match fs::metadata(filename) {
            Ok(meta) => meta.len() as i64,
            Err(_) => -1
        }
    }
    
    pub fn pipit_read_file(filename: &str) -> String {
        fs::read_to_string(filename).unwrap_or_else(|_| "".to_string())
    }
    
    pub fn pipit_write_file(filename: &str, content: &str) -> bool {
        fs::write(filename, content).is_ok()
    }
    
    pub fn pipit_file_exists(filename: &str) -> bool {
        Path::new(filename).exists()
    }
    
    pub fn pipit_remove_file(filename: &str) -> bool {
        fs::remove_file(filename).is_ok()
    }
    
    pub fn pipit_rename_file(old_name: &str, new_name: &str) -> bool {
        fs::rename(old_name, new_name).is_ok()
    }
    
    pub fn pipit_getcwd() -> String {
        std::env::current_dir()
            .unwrap_or_else(|_| std::path::PathBuf::from(""))
            .to_string_lossy()
            .to_string()
    }
    
    pub fn pipit_mkdir(path: &str) -> bool {
        fs::create_dir(path).is_ok()
    }
    
    pub fn pipit_rmdir(path: &str) -> bool {
        fs::remove_dir(path).is_ok()
    }
    
    pub fn pipit_get_file_info(_filename: &str) -> i64 {
        0 // 简化实现
    }
    
    pub fn pipit_read_buffer(_filename: &str, _buffer: &mut [u8], _size: usize) -> i32 {
        0
    }
    
    pub fn pipit_write_buffer(_filename: &str, _buffer: &[u8], _size: usize) -> i32 {
        0
    }
    
    pub fn pipit_line_reader_open(_filename: &str) -> *mut c_void {
        std::ptr::null_mut()
    }
    
    pub fn pipit_line_reader_next(_reader: *mut c_void) -> String {
        "".to_string()
    }
    
    pub fn pipit_line_reader_close(_reader: *mut c_void) -> i32 {
        0
    }
    
    // Math 模块函数实现
    pub fn pipit_add(a: i32, b: i32) -> i32 {
        a + b
    }
    
    pub fn pipit_subtract(a: i32, b: i32) -> i32 {
        a - b
    }
    
    pub fn pipit_multiply(a: i32, b: i32) -> i32 {
        a * b
    }
    
    pub fn pipit_divide(a: i32, b: i32) -> i32 {
        if b == 0 { 0 } else { a / b }
    }
    
    pub fn pipit_modulo(a: i32, b: i32) -> i32 {
        if b == 0 { 0 } else { a % b }
    }
    
    pub fn pipit_power(base: f64, exponent: f64) -> f64 {
        base.powf(exponent)
    }
    
    pub fn pipit_sqrt(x: f64) -> f64 {
        x.sqrt()
    }
    
    pub fn pipit_abs(x: i32) -> i32 {
        x.abs()
    }
    
    pub fn pipit_max(a: i32, b: i32) -> i32 {
        a.max(b)
    }
    
    pub fn pipit_min(a: i32, b: i32) -> i32 {
        a.min(b)
    }
    
    pub fn pipit_round(x: f64) -> f64 {
        x.round()
    }
    
    pub fn pipit_floor(x: f64) -> f64 {
        x.floor()
    }
    
    pub fn pipit_ceil(x: f64) -> f64 {
        x.ceil()
    }
    
    pub fn pipit_random() -> i32 {
        use rand::Rng;
        let mut rng = rand::thread_rng();
        rng.gen_range(0..10000)
    }
    
    pub fn pipit_srand(_seed: u32) {
        // 简化实现
    }
    
    pub fn pipit_random_range(min: i32, max: i32) -> i32 {
        use rand::Rng;
        let mut rng = rand::thread_rng();
        rng.gen_range(min..=max)
    }
    
    pub fn pipit_sin(x: f64) -> f64 {
        x.sin()
    }
    
    pub fn pipit_cos(x: f64) -> f64 {
        x.cos()
    }
    
    pub fn pipit_tan(x: f64) -> f64 {
        x.tan()
    }
    
    pub fn pipit_log(x: f64) -> f64 {
        x.ln()
    }
    
    pub fn pipit_log10(x: f64) -> f64 {
        x.log10()
    }
    
    pub fn pipit_exp(x: f64) -> f64 {
        x.exp()
    }
    
    pub fn pipit_random_float() -> f64 {
        use rand::Rng;
        let mut rng = rand::thread_rng();
        rng.gen_range(0.0..1.0)
    }
    
    pub fn pipit_is_prime(n: i32) -> bool {
        if n <= 1 { return false; }
        if n <= 3 { return true; }
        if n % 2 == 0 || n % 3 == 0 { return false; }
        let mut i = 5;
        while i * i <= n {
            if n % i == 0 || n % (i + 2) == 0 { return false; }
            i += 6;
        }
        true
    }
    
    pub fn pipit_factorial(n: i32) -> i64 {
        if n <= 1 { return 1; }
        (2..=n).product()
    }
    
    pub fn pipit_gcd(a: i32, b: i32) -> i32 {
        let (mut a, mut b) = (a, b);
        while b != 0 {
            let temp = b;
            b = a % b;
            a = temp;
        }
        a
    }
    
    pub fn pipit_lcm(a: i32, b: i32) -> i32 {
        if a == 0 || b == 0 { return 0; }
        (a * b).abs() / pipit_gcd(a, b)
    }
    
    pub fn pipit_degrees_to_radians(degrees: f64) -> f64 {
        degrees * std::f64::consts::PI / 180.0
    }
    
    pub fn pipit_radians_to_degrees(radians: f64) -> f64 {
        radians * 180.0 / std::f64::consts::PI
    }
    
    // String 模块函数实现
    pub fn pipit_string_length(s: &str) -> i32 {
        s.len() as i32
    }
    
    pub fn pipit_string_concat(s1: &str, s2: &str) -> String {
        format!("{}{}", s1, s2)
    }
    
    pub fn pipit_string_to_upper(s: &str) -> String {
        s.to_uppercase()
    }
    
    pub fn pipit_string_to_lower(s: &str) -> String {
        s.to_lowercase()
    }
    
    pub fn pipit_string_compare(s1: &str, s2: &str) -> i32 {
        s1.cmp(s2) as i32
    }
    
    pub fn pipit_string_find(s: &str, substr: &str) -> i32 {
        match s.find(substr) {
            Some(pos) => pos as i32,
            None => -1
        }
    }
    
    pub fn pipit_string_split(s: &str, delimiter: &str) -> Vec<String> {
        s.split(delimiter).map(|s| s.to_string()).collect()
    }
    
    pub fn pipit_string_replace(s: &str, from: &str, to: &str) -> String {
        s.replace(from, to)
    }
    
    pub fn pipit_string_trim(s: &str) -> String {
        s.trim().to_string()
    }
    
    pub fn pipit_string_substring(s: &str, start: i32, length: i32) -> String {
        let start = start.max(0) as usize;
        let end = (start + length.max(0) as usize).min(s.len());
        if start >= s.len() {
            return "".to_string();
        }
        s[start..end].to_string()
    }
    
    pub fn pipit_string_starts_with(s: &str, prefix: &str) -> bool {
        s.starts_with(prefix)
    }
    
    pub fn pipit_string_ends_with(s: &str, suffix: &str) -> bool {
        s.ends_with(suffix)
    }
    
    pub fn pipit_string_to_int(s: &str) -> i32 {
        s.parse().unwrap_or(0)
    }
    
    pub fn pipit_string_to_double(s: &str) -> f64 {
        s.parse().unwrap_or(0.0)
    }
    
    pub fn pipit_string_format(_format: &str, _args: &[&str]) -> String {
        "".to_string() // 简化实现
    }
    
    pub fn pipit_string_split_free(_strings: *mut *mut c_char) {
        // 简化实现
    }
    
    // 其他函数实现
    pub fn read_int() -> i32 {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap_or_default();
        input.trim().parse().unwrap_or(0)
    }
    
    pub fn read_float() -> f64 {
        let mut input = String::new();
        io::stdin().read_line(&mut input).unwrap_or_default();
        input.trim().parse().unwrap_or(0.0)
    }
    
    pub fn get_time() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64
    }
    
    pub fn strdup(s: &str) -> String {
        s.to_string()
    }
    
    pub fn vsnprintf(buffer: &mut [u8], format: &str, args: &[&str]) -> usize {
        let mut out = format.to_string();
        for a in args.iter() {
            out = out.replacen("%d", a, 1);
            out = out.replacen("%f", a, 1);
            out = out.replacen("%s", a, 1);
        }
        let bytes = out.as_bytes();
        let len = std::cmp::min(buffer.len().saturating_sub(1), bytes.len());
        if len > 0 { buffer[..len].copy_from_slice(&bytes[..len]); }
        if buffer.len() > 0 { buffer[len] = 0; }
        len
    }
    
    pub fn rmdir(path: &str) -> bool {
        fs::remove_dir(path).is_ok()
    }
}

// C绑定声明
#[cfg(feature = "use_c_stdlib")]
pub mod c_bindings {
    use super::*;
    
    // 定义FILE结构体
    #[repr(C)]
    pub struct FILE {
        // 简化实现
        _data: [u8; 0],
    }
    
    // 在Windows上使用动态链接库
    #[cfg(target_os = "windows")]
    #[link(name = "pipit_stdlib", kind = "dylib")]
    extern "C" {
        // IO 模块
        pub fn pipit_fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE;
        pub fn pipit_fclose(stream: *mut FILE) -> c_int;
        pub fn pipit_fread(ptr: *mut c_void, size: usize, nmemb: usize, stream: *mut FILE) -> usize;
        pub fn pipit_fwrite(ptr: *const c_void, size: usize, nmemb: usize, stream: *mut FILE) -> usize;
        pub fn pipit_feof(stream: *mut FILE) -> c_int;
        pub fn pipit_file_size(filename: *const c_char) -> i64;
        pub fn pipit_read_file(filename: *const c_char, buffer: *mut c_char, size: usize) -> c_int;
        pub fn pipit_write_file(filename: *const c_char, content: *const c_char) -> c_int;
        pub fn pipit_file_exists(filename: *const c_char) -> c_int;
        pub fn pipit_remove_file(filename: *const c_char) -> c_int;
        pub fn pipit_rename_file(old_name: *const c_char, new_name: *const c_char) -> c_int;
        pub fn pipit_getcwd(buffer: *mut c_char, size: usize) -> *mut c_char;
        pub fn pipit_mkdir(path: *const c_char) -> c_int;
        pub fn pipit_rmdir(path: *const c_char) -> c_int;
        
        // Math 模块
        pub fn pipit_add(a: c_int, b: c_int) -> c_int;
        pub fn pipit_subtract(a: c_int, b: c_int) -> c_int;
        pub fn pipit_multiply(a: c_int, b: c_int) -> c_int;
        pub fn pipit_divide(a: c_int, b: c_int) -> c_int;
        pub fn pipit_modulo(a: c_int, b: c_int) -> c_int;
        pub fn pipit_power(base: c_double, exponent: c_double) -> c_double;
        pub fn pipit_sqrt(x: c_double) -> c_double;
        pub fn pipit_abs(x: c_int) -> c_int;
        
        // String 模块
        pub fn pipit_string_length(s: *const c_char) -> c_int;
        pub fn pipit_string_concat(s1: *const c_char, s2: *const c_char) -> *mut c_char;
        pub fn pipit_string_to_upper(s: *mut c_char);
        pub fn pipit_string_to_lower(s: *mut c_char);
        
        // 其他函数
        pub fn pipit_read_int() -> c_int;
        pub fn pipit_read_float() -> c_double;
        pub fn pipit_get_time() -> u64;
        pub fn strdup(s: *const c_char) -> *mut c_char;
        pub fn vsnprintf(buffer: *mut c_char, size: usize, format: *const c_char, args: *const c_char) -> c_int;
        pub fn getcwd(buffer: *mut c_char, size: usize) -> *mut c_char;
        pub fn rmdir(path: *const c_char) -> c_int;
        
        // 其他标准库函数...
    }
    
    // 在非Windows平台上使用静态链接库
    #[cfg(not(target_os = "windows"))]
    #[link(name = "pipit_stdlib", kind = "static")]
    extern "C" {
        // IO 模块
        pub fn pipit_fopen(filename: *const c_char, mode: *const c_char) -> *mut FILE;
        pub fn pipit_fclose(stream: *mut FILE) -> c_int;
        pub fn pipit_fread(ptr: *mut c_void, size: usize, nmemb: usize, stream: *mut FILE) -> usize;
        pub fn pipit_fwrite(ptr: *const c_void, size: usize, nmemb: usize, stream: *mut FILE) -> usize;
        pub fn pipit_feof(stream: *mut FILE) -> c_int;
        pub fn pipit_file_size(filename: *const c_char) -> i64;
        pub fn pipit_read_file(filename: *const c_char, buffer: *mut c_char, size: usize) -> c_int;
        pub fn pipit_write_file(filename: *const c_char, content: *const c_char) -> c_int;
        pub fn pipit_file_exists(filename: *const c_char) -> c_int;
        pub fn pipit_remove_file(filename: *const c_char) -> c_int;
        pub fn pipit_rename_file(old_name: *const c_char, new_name: *const c_char) -> c_int;
        pub fn pipit_getcwd(buffer: *mut c_char, size: usize) -> *mut c_char;
        pub fn pipit_mkdir(path: *const c_char) -> c_int;
        pub fn pipit_rmdir(path: *const c_char) -> c_int;
        
        // Math 模块
        pub fn pipit_add(a: c_int, b: c_int) -> c_int;
        pub fn pipit_subtract(a: c_int, b: c_int) -> c_int;
        pub fn pipit_multiply(a: c_int, b: c_int) -> c_int;
        pub fn pipit_divide(a: c_int, b: c_int) -> c_int;
        pub fn pipit_modulo(a: c_int, b: c_int) -> c_int;
        pub fn pipit_power(base: c_double, exponent: c_double) -> c_double;
        pub fn pipit_sqrt(x: c_double) -> c_double;
        pub fn pipit_abs(x: c_int) -> c_int;
        
        // String 模块
        pub fn pipit_string_length(s: *const c_char) -> c_int;
        pub fn pipit_string_concat(s1: *const c_char, s2: *const c_char) -> *mut c_char;
        pub fn pipit_string_to_upper(s: *mut c_char);
        pub fn pipit_string_to_lower(s: *mut c_char);
        
        // 其他函数
        pub fn pipit_read_int() -> c_int;
        pub fn pipit_read_float() -> c_double;
        pub fn pipit_get_time() -> u64;
        pub fn strdup(s: *const c_char) -> *mut c_char;
        pub fn vsnprintf(buffer: *mut c_char, size: usize, format: *const c_char, args: *const c_char) -> c_int;
        pub fn getcwd(buffer: *mut c_char, size: usize) -> *mut c_char;
        pub fn rmdir(path: *const c_char) -> c_int;
        
        // 其他标准库函数...
    }
}

// 定义FILE结构体（非C绑定模式下使用）
#[cfg(not(feature = "use_c_stdlib"))]
#[repr(C)]
pub struct FILE {
    // 简化实现
    _data: [u8; 0],
}

// 原生函数适配器

// 常用标准库函数适配器
#[cfg(not(feature = "use_c_stdlib"))]
fn native_read_int(vm: &mut VirtualMachine) {
    let v = stdlib_functions::read_int();
    vm.stack.push(Value::Integer(v));
}

#[cfg(feature = "use_c_stdlib")]
fn native_read_int(vm: &mut VirtualMachine) {
    let v = unsafe { c_bindings::pipit_read_int() };
    vm.stack.push(Value::Integer(v as i32));
}

#[cfg(not(feature = "use_c_stdlib"))]
fn native_read_float(vm: &mut VirtualMachine) {
    let v = stdlib_functions::read_float();
    vm.stack.push(Value::Float(v));
}

#[cfg(feature = "use_c_stdlib")]
fn native_read_float(vm: &mut VirtualMachine) {
    let v = unsafe { c_bindings::pipit_read_float() };
    vm.stack.push(Value::Float(v));
}

#[cfg(not(feature = "use_c_stdlib"))]
fn native_get_time(vm: &mut VirtualMachine) {
    let t = stdlib_functions::get_time();
    vm.stack.push(Value::Integer((t & 0xFFFFFFFF) as i32));
}

#[cfg(feature = "use_c_stdlib")]
fn native_get_time(vm: &mut VirtualMachine) {
    let t = unsafe { c_bindings::pipit_get_time() };
    vm.stack.push(Value::Integer((t & 0xFFFFFFFF) as i32));
}

fn native_print(vm: &mut VirtualMachine) {
    if let Some(v) = vm.stack.pop() {
        match v {
            Value::Integer(i) => print!("{}", i),
            Value::Float(f) => print!("{}", f),
            Value::Boolean(b) => print!("{}", b),
            Value::String(s) => print!("{}", s),
            _ => print!("{:?}", v),
        }
        let _ = std::io::stdout().flush();
    }
}

fn native_println(vm: &mut VirtualMachine) {
    if let Some(v) = vm.stack.pop() {
        match v {
            Value::Integer(i) => println!("{}", i),
            Value::Float(f) => println!("{}", f),
            Value::Boolean(b) => println!("{}", b),
            Value::String(s) => println!("{}", s),
            _ => println!("{:?}", v),
        }
    }
}

#[cfg(not(feature = "use_c_stdlib"))]
fn native_strdup(vm: &mut VirtualMachine) {
    if let Some(Value::String(s)) = vm.stack.pop() {
        let result = stdlib_functions::strdup(&s);
        vm.stack.push(Value::String(result));
    } else {
        vm.stack.push(Value::String("".to_string()));
    }
}

#[cfg(feature = "use_c_stdlib")]
fn native_strdup(vm: &mut VirtualMachine) {
    if let Some(Value::String(s)) = vm.stack.pop() {
        let c_str = CString::new(s).unwrap_or_default();
        let result = unsafe { c_bindings::strdup(c_str.as_ptr()) };
        if !result.is_null() {
            let rust_str = unsafe { CStr::from_ptr(result).to_string_lossy().to_string() };
            unsafe { libc::free(result as *mut libc::c_void); }
            vm.stack.push(Value::String(rust_str));
        } else {
            vm.stack.push(Value::String("".to_string()));
        }
    } else {
        vm.stack.push(Value::String("".to_string()));
    }
}

#[cfg(not(feature = "use_c_stdlib"))]
fn native_vsnprintf(vm: &mut VirtualMachine) {
    // 简化实现，实际应处理可变参数
    vm.stack.push(Value::Integer(0));
}

#[cfg(feature = "use_c_stdlib")]
fn native_vsnprintf(vm: &mut VirtualMachine) {
    // 简化实现，实际应处理可变参数
    vm.stack.push(Value::Integer(0));
}

#[cfg(not(feature = "use_c_stdlib"))]
fn native_rmdir(vm: &mut VirtualMachine) {
    if let Some(Value::String(path)) = vm.stack.pop() {
        let result = stdlib_functions::rmdir(&path);
        vm.stack.push(Value::Boolean(result));
    } else {
        vm.stack.push(Value::Boolean(false));
    }
}

#[cfg(feature = "use_c_stdlib")]
fn native_rmdir(vm: &mut VirtualMachine) {
    if let Some(Value::String(path)) = vm.stack.pop() {
        let c_path = CString::new(path).unwrap_or_default();
        let result = unsafe { c_bindings::rmdir(c_path.as_ptr()) };
        vm.stack.push(Value::Boolean(result == 0));
    } else {
        vm.stack.push(Value::Boolean(false));
    }
}

// IO模块函数适配器
#[cfg(not(feature = "use_c_stdlib"))]
fn native_pipit_fopen(vm: &mut VirtualMachine) {
    if let (Some(Value::String(mode)), Some(Value::String(filename))) = (vm.stack.pop(), vm.stack.pop()) {
        let result = stdlib_functions::pipit_fopen(&filename, &mode);
        vm.stack.push(Value::Pointer(result as *mut c_void));
    } else {
        vm.stack.push(Value::Pointer(std::ptr::null_mut()));
    }
}

#[cfg(feature = "use_c_stdlib")]
fn native_pipit_fopen(vm: &mut VirtualMachine) {
    if let (Some(Value::String(mode)), Some(Value::String(filename))) = (vm.stack.pop(), vm.stack.pop()) {
        let c_filename = CString::new(filename).unwrap_or_default();
        let c_mode = CString::new(mode).unwrap_or_default();
        let result = unsafe { c_bindings::pipit_fopen(c_filename.as_ptr(), c_mode.as_ptr()) };
        vm.stack.push(Value::Pointer(result as *mut c_void));
    } else {
        vm.stack.push(Value::Pointer(std::ptr::null_mut()));
    }
}

// 这里省略其他函数适配器的实现，实际实现中需要包含所有126个函数的适配器

// 其他模块函数适配器...

// Math模块函数适配器
#[cfg(not(feature = "use_c_stdlib"))]
fn native_pipit_add(vm: &mut VirtualMachine) {
    if let (Some(Value::Integer(b)), Some(Value::Integer(a))) = (vm.stack.pop(), vm.stack.pop()) {
        let result = stdlib_functions::pipit_add(a, b);
        vm.stack.push(Value::Integer(result));
    } else {
        vm.stack.push(Value::Integer(0));
    }
}

#[cfg(feature = "use_c_stdlib")]
fn native_pipit_add(vm: &mut VirtualMachine) {
    if let (Some(Value::Integer(b)), Some(Value::Integer(a))) = (vm.stack.pop(), vm.stack.pop()) {
        let result = unsafe { c_bindings::pipit_add(a as c_int, b as c_int) };
        vm.stack.push(Value::Integer(result as i32));
    } else {
        vm.stack.push(Value::Integer(0));
    }
}

// 其他Math函数适配器...

// String模块函数适配器
#[cfg(not(feature = "use_c_stdlib"))]
fn native_pipit_string_length(vm: &mut VirtualMachine) {
    if let Some(Value::String(s)) = vm.stack.pop() {
        let result = stdlib_functions::pipit_string_length(&s);
        vm.stack.push(Value::Integer(result));
    } else {
        vm.stack.push(Value::Integer(0));
    }
}

#[cfg(feature = "use_c_stdlib")]
fn native_pipit_string_length(vm: &mut VirtualMachine) {
    if let Some(Value::String(s)) = vm.stack.pop() {
        let c_str = CString::new(s).unwrap_or_default();
        let result = unsafe { c_bindings::pipit_string_length(c_str.as_ptr()) };
        vm.stack.push(Value::Integer(result as i32));
    } else {
        vm.stack.push(Value::Integer(0));
    }
}

// 其他String函数适配器...

// OS模块函数适配器
#[cfg(not(feature = "use_c_stdlib"))]
fn native_pipit_os_system(vm: &mut VirtualMachine) {
    if let Some(Value::String(command)) = vm.stack.pop() {
        let result = std::process::Command::new("cmd")
            .arg("/c")
            .arg(&command)
            .status()
            .map(|s| s.code().unwrap_or(-1))
            .unwrap_or(-1);
        vm.stack.push(Value::Integer(result));
    } else {
        vm.stack.push(Value::Integer(-1));
    }
}

#[cfg(feature = "use_c_stdlib")]
fn native_pipit_os_system(vm: &mut VirtualMachine) {
    if let Some(Value::String(command)) = vm.stack.pop() {
        let c_cmd = CString::new(command).unwrap_or_default();
        let result = unsafe { libc::system(c_cmd.as_ptr()) };
        vm.stack.push(Value::Integer(result as i32));
    } else {
        vm.stack.push(Value::Integer(-1));
    }
}

// 其他OS函数适配器...

// 这里省略其他模块的函数适配器实现

// 默认的标准库注册函数，保持与现有代码的兼容性
/// 将标准库函数注册到虚拟机
pub fn register_stdlib_functions(vm: &mut crate::vm::VirtualMachine) {
    let stdlib = StandardLibrary::new(StdlibModuleConfig::default());
    stdlib.register_all(vm);
}